﻿using mshtml;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace IE
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            mInfoOutputList = new List<ClientInfoOutput>();
            mConfig = new Config();
            string defaultDir = System.Windows.Forms.Application.StartupPath;
            string loadConfigPath = defaultDir + Path.DirectorySeparatorChar + "config.xml";
            try
            {
                mConfig = Config.loadConfig(loadConfigPath);
            }
            catch (Exception e)
            {
                Config.saveConfig(loadConfigPath, mConfig);
            }
            textBoxUserName.Text = mConfig.UserName;
            textBoxPassword.Text = mConfig.Password;
            textBoxLoadFilePath.Text = mConfig.LoadInfoPath;
            catchData.Enabled = false;
            mInputInfo = readInputInfo(mConfig.LoadInfoPath, "Sheet1");
            mCatchDataReady = false;
        }

        private List<ClientInfoOutput> mInfoOutputList;
        private IList<ClientInfoInput> mInputInfo;
        private bool mDumpReady = false;
        private bool mCatchDataReady = false;
        private Config mConfig;
        private DataTable mTable;

        private void button1_Click(object sender, EventArgs e)
        {
            SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer();
            ie.DocumentComplete += documentComplete;
            ie.Navigate("http://crm.9fbank.com");
            ie.Visible = true;
            waitForCatchDataReady();
            catchData.Enabled = mCatchDataReady;
        }
        private void documentComplete(object pDisp, ref object URL)
        {
            if (URL.ToString().Equals("http://crm.9fbank.com/"))
            {
                SHDocVw.InternetExplorer ie = pDisp as SHDocVw.InternetExplorer;
                if (ie != null)
                {
                    login(ie);
                    mCatchDataReady = true;
                }
            }
            if (URL.ToString().Equals("http://crm.9fbank.com/crm/userCenter/clientBinding.html"))
            {
                SHDocVw.InternetExplorer ie = pDisp as SHDocVw.InternetExplorer;
                if (ie != null)
                {
                    if (mInputInfo.Count > 0)
                    {
                        ClientInfoInput c = mInputInfo[0];
                        if (c != null)
                        {
                            searchData(ie, c);
                            mInputInfo.RemoveAt(0);
                        }
                    }
                    else
                    {
                        mDumpReady = true;
                    }
                }
            }
            if (URL.ToString().Equals("http://crm.9fbank.com/crm/userCenter/serchByName.html"))
            {
                SHDocVw.InternetExplorer ie = pDisp as SHDocVw.InternetExplorer;
                if (ie != null)
                {
                    List<ClientInfoOutput> infoList = fetchData(ie);
                    if (infoList != null)
                    {
                        mInfoOutputList.AddRange(infoList);
                        mInfoOutputList = mInfoOutputList.Distinct(new ClientInfoComparer()).ToList();
                    }
                    ie.Navigate("http://crm.9fbank.com/crm/userCenter/clientBinding.html");
                }
            }
        }

        private void bindClientAndSearch(object sender, EventArgs e)
        {
            mDumpReady = false;
            dumpData.Enabled = false;
            SHDocVw.InternetExplorer ie = new SHDocVw.InternetExplorer();
            ie.DocumentComplete += documentComplete;
            ie.Navigate("http://crm.9fbank.com/crm/userCenter/clientBinding.html");
            ie.Visible = true;
            waitForDumpReady();
        }

        private void waitForDumpReady()
        {
            while (mDumpReady != true)
            {
                Application.DoEvents();
            }
            dumpData.Enabled = true;
        }

        private void waitForCatchDataReady()
        {
            while (mCatchDataReady != true)
            {
                Application.DoEvents();
            }
            catchData.Enabled = true;
        }

        private void login(SHDocVw.InternetExplorer ie)
        {
            mshtml.IHTMLDocument2 doc = ie.Document;
            if (doc != null)
            {
                IHTMLElementCollection all = doc.all;
                if (all != null)
                {
                    mshtml.IHTMLElementCollection inputs;
                    inputs = all.tags("INPUT");
                    mshtml.IHTMLInputElement loginname = inputs.item("email", 0) as mshtml.IHTMLInputElement;
                    mshtml.IHTMLInputElement password = inputs.item("password", 0) as mshtml.IHTMLInputElement;
                    mshtml.IHTMLElement login = inputs.item("button", 0);
                    if (loginname != null && password != null)
                    {
                        loginname.value = mConfig.UserName;
                        password.value = mConfig.Password;
                        login.click();
                    }
                }
            }
        }

        private void searchData(SHDocVw.InternetExplorer ie, ClientInfoInput info)
        {
            mshtml.IHTMLDocument2 doc = ie.Document;
            if (doc != null)
            {
                IHTMLElementCollection all = doc.all;
                if (all != null)
                {
                    mshtml.IHTMLElementCollection inputs;
                    inputs = all.tags("INPUT");
                    mshtml.IHTMLInputElement realName = inputs.item("realName", 0) as mshtml.IHTMLInputElement;
                    mshtml.IHTMLInputElement idCardNo = inputs.item("idCardNo", 0) as mshtml.IHTMLInputElement;
                    mshtml.IHTMLInputElement mobile = inputs.item("mobile", 0) as mshtml.IHTMLInputElement;


                    mshtml.IHTMLElement search = inputs.item("button", 0);
                    if (realName != null && idCardNo != null && mobile != null)
                    {
                        realName.value = info.ClientName;
                        idCardNo.value = info.ClientID;
                        mobile.value = info.ClientMobile;
                        search.click();
                    }
                }
            }
        }

        private List<ClientInfoOutput> fetchData(SHDocVw.InternetExplorer ie)
        {
            mshtml.IHTMLDocument2 doc = ie.Document;
            if (doc == null)
                return null;
            IHTMLElementCollection all = doc.all;
            if (all == null)
                return null;
            mshtml.IHTMLElementCollection divs;
            divs = all.tags("DIV");
            IHTMLElement targetDiv = null;
            foreach (IHTMLElement ele in divs)
            {
                if (ele.className == "crm-uesrlist")
                {
                    targetDiv = ele;
                    break;
                }
            }
            if (targetDiv == null)
                return null;
            IHTMLElementCollection tables = targetDiv.children as IHTMLElementCollection;
            if (tables == null)
                return null;
            List<ClientInfoOutput> infoList = new List<ClientInfoOutput>();
            foreach (IHTMLTable table in tables)
            {
                IHTMLElementCollection tableRows = table.rows;
                if (tableRows != null)
                {
                    foreach (IHTMLTableRow row in tableRows)
                    {
                        IHTMLElementCollection cells = row.cells;
                        if (cells != null)
                        {
                            ClientInfoOutput info = new ClientInfoOutput();
                            IEnumerator ienum = cells.GetEnumerator();
                            while (ienum.MoveNext())
                            {
                                IHTMLElement node = (IHTMLElement)ienum.Current;
                                string innerText = node.innerText;
                                info.DumpInfo.Add(innerText);
                            }
                            infoList.Add(info);
                        }
                    }
                }
            }
            return infoList.Count == 0 ? null : infoList;
        }

        private void dumpData_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            System.Collections.IEnumerator outputList = mInfoOutputList.GetEnumerator();
            if (mInfoOutputList.Count > 1)
            {
                outputList.MoveNext();
                ClientInfoOutput titleRow = outputList.Current as ClientInfoOutput;
                foreach(string content in titleRow.DumpInfo)
                {
                    dt.Columns.Add(content);
                }
               
                while (outputList.MoveNext())
                {
                    ClientInfoOutput realContent = outputList.Current as ClientInfoOutput;
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < realContent.DumpInfo.Count; ++i)
                    {
                        dr[i] = realContent.DumpInfo[i];
                    }
                    dt.Rows.Add(dr);
                }
                LoadTable tableView = new LoadTable();
                tableView.refreshData(dt);
                saveFileDialog1.Filter = "Excel Workbook(*.xlsx) | *.xlsx | Excel files(*.xls) | *.xls";
                saveFileDialog1.RestoreDirectory = true;
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    mConfig.SaveFilePath = saveFileDialog1.FileName.ToString();
                    ExcelHelper helper = new ExcelHelper(mConfig.SaveFilePath);
                    helper.DataTableToExcel(dt, "Client Data Read from Website", true);
                    tableView.ShowDialog();
                }
            }
        }

        private void loadFileButton_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Excel Workbook(*.xlsx)|*.xlsx|Excel files(*.xls)|*.xls";
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.InitialDirectory = textBoxLoadFilePath.Text;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBoxLoadFilePath.Text = openFileDialog1.FileName.ToString(); //获得文件路径 
                string defaultDir = System.Windows.Forms.Application.StartupPath;
                string loadConfigPath = defaultDir + Path.DirectorySeparatorChar + "config.xml";
                mConfig.LoadInfoPath = textBoxLoadFilePath.Text;
                Config.saveConfig(loadConfigPath, mConfig);
                mInputInfo = readInputInfo(mConfig.LoadInfoPath, "Sheet1");
                LoadTable tableView = new LoadTable();
                tableView.refreshData(mTable);
                tableView.ShowDialog();
            }
        }

        private IList<ClientInfoInput> readInputInfo(string loadFilePath, string sheetName)
        {
            if (!File.Exists(loadFilePath))
            {
                MessageBox.Show(String.Format("File {0} does not Exist", loadFilePath));
                return null;
            }
            ExcelHelper helper = new ExcelHelper(loadFilePath);
            mTable = helper.ExcelToDataTable(sheetName, true);
            IList<ClientInfoInput> users = ModelConvertHelper<ClientInfoInput>.ConvertToModel(mTable);
            return users;
        }

        private void reloadInfoButton_Click(object sender, EventArgs e)
        {
            mInputInfo = readInputInfo(mConfig.LoadInfoPath, "Sheet1");
        }
    }
}
